package com.ljfresh.customer.utils.udesk;

import com.alibaba.fastjson.JSON;
import com.ljfresh.customer.dto.udesk.*;
import com.ljfresh.customer.page.PageResult;
import com.ljfresh.customer.param.CustomerCreateParam;
import com.ljfresh.customer.param.CustomerParam;
import com.ljfresh.customer.param.CustomerReplyParam;
import com.ljfresh.customer.param.TicketCreateParam;
import com.ljfresh.customer.pojo.*;
import com.ljfresh.customer.result.TicketDetailResult;
import com.ljfresh.customer.utils.base.HttpClientUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;


/**
 * @Author zzx
 */
public class    UDeskBasicApiUtil {
//email=281721414@qq.com&nonce=a0eeb329-0778-42ac-ae86-7e5a2f183cbb&num=%23157612&sign=293064718205772d6fc5b3adea71b70dab0f3dafbd913055e989e5611284dfcb&timestamp=1587539981530
    /**
     * 查看工单详情
     * id: 工单id
     * num:
     * @return
     */
    public static TicketDetailResult detailFind(Integer id, String num) {

        String paramStr=UDeskParamBuilder.generateDetailParam(id,num);

        try {
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.DETAIL_TICKET_URL, paramStr);
            System.out.println(resultStr);
            TicketDetailResult result = JSON.parseObject(resultStr, TicketDetailResult.class);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;//todo:设置状态码 设置异常?
    }


    /**
     * 创建工单
     * @return
     */
    public static TicketCreateResult createWorkOrder(WorkOrder workOrder) {

        String paramStr=UDeskParamBuilder.generateURLParam();
        TicketCreateParam createParam = new TicketCreateParam();
        Ticket ticket = new Ticket();
        TicketField ticketField = new TicketField();
        ticket.setSubject(workOrder.getStoreName()+workOrder.getCreator()+"的工单");
        ticket.setContent(workOrder.getSubject());
        ticket.setTemplate_id(112371);
        ticket.setType("cellphone");
        ticket.setPriority("标准");
        ticket.setStatus("开启");
        ticket.setType_content(workOrder.getCellphone());

        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //ticketField.setTextField_35774(dateFormatter.format(workOrder.getArrivalTime()));//到货时间
        ticketField.setTextField_35834(workOrder.getStoreId());
        ticketField.setTextField_35836(workOrder.getStoreName());
        ticketField.setTextField_35775(workOrder.getGoodsId());
        ticketField.setTextField_35831(workOrder.getEmail());
        ticketField.setTextField_35835(workOrder.getGoodsName());
        ticketField.setTextField_125641(workOrder.getGoodsUnit());
        ticketField.setTextField_125631(workOrder.getPricePerUnit());
        ticketField.setTextField_35776(workOrder.getGoodsNum());
        ticketField.setTextField_35777(workOrder.getRealGoodsNum());
        ticketField.setSelectField_19468(null);//ticketField.setSelectField_19468(workOrder.getOrderType());
        ticketField.setTextField_38627(workOrder.getArrivalTime());
        ticketField.setTextField_38643(workOrder.getCreateTime());
        ticketField.setTextField_50511(workOrder.getCreator());
        ticketField.setTextField_131421(workOrder.getOrder_fid());//调入单
        ticket.setTicket_field(ticketField);
        createParam.setTicket(ticket);
        TicketCreateResult result = new TicketCreateResult();
        try {
            String resultStr = HttpClientUtil.getApiJsonForHttpsJsonType(UDeskConst.TICKETS_CREATE_URL, paramStr, JSON.toJSONString(createParam));
            System.out.println(resultStr);
            result = JSON.parseObject(resultStr, TicketCreateResult.class);
            //return erpStore.getData();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


   /* *//**
     * 我的工单列表
     * @return
     *//*
    public static List<WorkOrder> branchFind() {
        String paramStr = UDeskParamBuilder.generateCustomRecordParam("UDesk");

        List<WorkOrder> list = new ArrayList<>();
        try {

            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }*/

    /**
     * 创建客户
     */
    public static CustomerCreateResult createCustom(CustomerCreateParam param) {
        String paramStr = UDeskParamBuilder.generateURLParam();
        try {
            String resultStr = HttpClientUtil.getApiJsonForHttpsJsonType(UDeskConst.CUSTOMER_CREATE_URL, paramStr,JSON.toJSONString(param));
            System.out.println(resultStr);
            CustomerCreateResult customerCreateResult = JSON.parseObject(resultStr, CustomerCreateResult.class);
            return customerCreateResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 查询客户详情
     * @return
     */
    public static CustomerDetailResult getCustomDetail(String type, String content) {
        String paramStr = UDeskParamBuilder.generateCustomParam(type,content);

        try {
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.CUSTOMER_DETAIL_URL, paramStr);
            System.out.println(resultStr);
            return JSON.parseObject(resultStr, CustomerDetailResult.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询客户记录
     * @return
     */
    public static CustomerRecordResult getCustomRecordList(String type,String content,Integer page,Integer page_size,Date date) {
        try {
            String paramStr = UDeskParamBuilder.generateCustomRecordParam(type,content,page,100);//设为最大 100
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.CUSTOMER_RECORD_URL, paramStr);
            System.out.println(resultStr);
            CustomerRecordResult customerRecordResult = JSON.parseObject(resultStr, CustomerRecordResult.class);
            List<Feed> feeds = customerRecordResult.getFeeds();
            /*if (date!=null) {
                if ((feeds.get(feeds.size() - 1).getCreated_at() != null && feeds.get(feeds.size() - 1).getCreated_at().after(date))
                        || (feeds.get(feeds.size() - 1).getTime() != null && feeds.get(feeds.size() - 1).getTime().after(date))) {//最后一条记录(time为变更记录,create_at为工单)的时间大于选择的日期,重新筛选(一般不出现)
                    //重新查询新的
                    resultStr = HttpClientUtil.getApiJson(UDeskConst.CUSTOMER_RECORD_URL, UDeskParamBuilder.generateCustomRecordParam(type, content, page + 1, 100));
                    customerRecordResult = JSON.parseObject(resultStr, CustomerRecordResult.class);
                }
            }*/

            /**1.过滤类型*/
            //定义filters
            Predicate<Feed> typeFilter = (f)->(f.getFeed_type().equals("Ticket") );
            List<Feed> newFeeds  = new ArrayList<>();
            //根据filters将数据放进新集合
            feeds.stream()
                    .filter(typeFilter)
                    .forEach((feed) -> newFeeds.add(feed));

            /**2.过滤时间*/
            if (date ==null){
                /**3.只做分页处理*/
                //customerRecordResult.setFeeds(newFeeds);
                int totalPage = newFeeds.size() / page_size>0?newFeeds.size() / page_size:1;
                PageResult<Feed> result = new PageResult<>();
                //截取page_size的
                if (newFeeds.size()>=page_size){
                    result.setList(newFeeds.subList(0, page_size));
                }else {
                    result.setList(newFeeds);
                }
                result.setPageSize(page_size);
                int count = newFeeds.size();
                result.setTotalCount(count);
                result.setTotalNum(totalPage);
                customerRecordResult.setFeedsPage(result);
            }else {
                   /* SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String time = dateFormat.format(date);//指定日期*/

                Predicate<Feed> timeFilter = (f)->(f.getCreated_at().equals(date));

                List<Feed> newFeeds2  = new ArrayList<>();
                newFeeds.stream()
                        .filter(timeFilter)
                        .forEach((feed) -> newFeeds2.add(feed));
                /**3.分页处理*/
                if (newFeeds2.size()>=page_size){
                    int totalPage = newFeeds2.size() / page_size>0?newFeeds2.size() / page_size:1;

                }else {
                    //TODO:处理不够的数据
                }
                int totalPage = newFeeds2.size() / page_size>0?newFeeds2.size() / page_size:1;
                PageResult<Feed> result = new PageResult<>();
                if (newFeeds2.size()>=page_size){
                    result.setList(newFeeds2.subList(0, page_size));
                }else {
                    result.setList(newFeeds2);
                }
                result.setPageNum(page);
                result.setPageSize(page_size);
                int count = newFeeds2.size();
                result.setTotalCount(count);
                result.setTotalNum(totalPage);
                customerRecordResult.setFeedsPage(result);
            }

            customerRecordResult.setFeeds(null);//清楚冗余数据 方便前端查看
            return customerRecordResult;
        } catch (IOException e) {
            e.printStackTrace();
            return new CustomerRecordResult(11111);
        }
    }

    /**
     * 获取工单过滤器列表
     * @return
     */
    public static List<WorkOrder> getOrderFilterList(String type,Integer id,Integer page,Integer per_page) {

        String paramStr=UDeskParamBuilder.generateFiltersParam(type,id,page,per_page);

        List<WorkOrder> list = new ArrayList<>();
        try {
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.FILTERS_URL, paramStr);
            System.out.println(resultStr);
            //WorkOrder erpStore = JacksonUtil.fromJson(resultStr, WorkOrder.class);
            //return erpStore.getData();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 获取特定工单过滤器下的工单
     * @return
     */
    public static TicketFilterResult getOrderListByFilter(Integer filterId, Integer page, Integer per_page) {

        String paramStr=UDeskParamBuilder.generateTicketInFiltersParam(filterId,page,per_page);

        List<WorkOrder> list = new ArrayList<>();
        try {
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.TICKETS_IN_FILTERS_URL, paramStr);
            System.out.println(resultStr);
            TicketFilterResult ticketFilterResult = JSON.parseObject(resultStr, TicketFilterResult.class);
            //return erpStore.getData();
            return ticketFilterResult;
        } catch (IOException e) {
            e.printStackTrace();//TODO:此处处理异常
            return null;
        }
    }


    /**
     * 工单回复上传附件
     * @return
     */
    public static UploadToReplyResult uploadFileForReply(MultipartFile multipartFile,Integer ticketId) {

        try {
            String fileName = getFileName(multipartFile);

            String paramStr=UDeskParamBuilder.generateUploadFileParam(ticketId,fileName,null);
            String resultStr = HttpClientUtil.getApiForUpload(UDeskConst.TICKETS_UPLOAD_FILE_FOR_REPLY_URL, paramStr,multipartFile,fileName);
            System.out.println(resultStr);
            UploadToReplyResult uploadToReplyResult = JSON.parseObject(resultStr, UploadToReplyResult.class);
            return uploadToReplyResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;//TODO:设置状态码
        }
    }


    /**
     * 客户回复
     * @return
     */
    public static CustomerReplyResult customerReply(CustomerReplyParam param) {

        String paramStr=UDeskParamBuilder.generateURLParam();

        try {
            String resultStr = HttpClientUtil.getApiJsonForHttpsJsonType(UDeskConst.TICKETS_CUSTOMER_REPLY_URL, paramStr,JSON.toJSONString(param));
            System.out.println(resultStr);
            CustomerReplyResult customerReplyResult = JSON.parseObject(resultStr, CustomerReplyResult.class);
            return customerReplyResult;
        } catch (IOException e) {
            e.printStackTrace();
            return new CustomerReplyResult(0);//TODO:处理状态码
        }
    }

    /**
     * 获取工单下所有回复
     * @return
     */
    public static AllReplyResult getAllReply(Long id,Integer pageNum,Integer pageSize) {

        String paramStr=UDeskParamBuilder.generateGetAllReplyParam(pageNum,pageSize);
        try {
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.TICKETS_BASE_URL,id,UDeskConst.REPLIES,paramStr);
            System.out.println(resultStr);
            AllReplyResult replyResult = JSON.parseObject(resultStr, AllReplyResult.class);
            return replyResult;
        } catch (IOException e) {
            e.printStackTrace();
            return new AllReplyResult(0);//TODO:处理状态码
        }
    }

    /**
     * 普通上传附件
     * @return
     */
    public static AttachmentUploadResult uploadFile(MultipartFile multipartFile,Integer ticketId) {

        try {
            String fileName = getFileName(multipartFile);
            String paramStr=UDeskParamBuilder.generateUploadFileParam(ticketId,fileName,null);

            String resultStr = HttpClientUtil.getApiForUpload(UDeskConst.TICKETS_UPLOAD_FILE_URL, paramStr,multipartFile,fileName);
            System.out.println(resultStr);
            AttachmentUploadResult attachmentUploadResult = JSON.parseObject(resultStr, AttachmentUploadResult.class);
            return attachmentUploadResult;
        } catch (Exception e) {
            e.printStackTrace();
            return new AttachmentUploadResult(1010);//TODO:修改状态码
        }
    }





    /**
     * 客户回复清空附件
     * @return
     */
    public static List<WorkOrder> deleteFileForReply(Integer ticketId) {

        String paramStr=UDeskParamBuilder.generateDeleteFileForReplyParam(ticketId);

        List<WorkOrder> list = new ArrayList<>();
        try {
            String resultStr = HttpClientUtil.getApiJsonForHttpsFormType(UDeskConst.TICKETS_CUSTOMER_REPLY_URL, paramStr);
            System.out.println(resultStr);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取工单模板列表
     * @return
     */
    public static List<WorkOrder> getTicketTemplates() {

        String paramStr=UDeskParamBuilder.generateTicketTemplatesParam();

        List<WorkOrder> list = new ArrayList<>();
        try {
            String resultStr = HttpClientUtil.getApiJson(UDeskConst.TICKET_TEMPLATES_URL, paramStr);
            System.out.println(resultStr);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }



    public static void main(String[] args) {
        //detailFind(null,"#172850");
        //detailFind(151964431,null);
        //CustomerCreateResult("id","1849729361",1, 100,null);
        //getCustomRecordList("cellphone","13100000002",1, 100);
        //getOrderFilterList("all",null,null, 50);
        //getOrderListByFilter(777001,null,null);
        //getTicketTemplates();
        //getCustomDetail("id",1799639691);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        /*WorkOrder workOrder = new WorkOrder(null,"2","shenYi店","",0,simpleDateFormat.format(new Date()),"测试shenYi店工单","64646964","柠檬","袋","5","2","2","何伟",simpleDateFormat.format(new Date()),"13100000002",null,null);
        createWorkOrder(workOrder);*/

        //Customer customer = new Customer(null,null,null,null,"韩总", null, "技术经理", null, null, null, null,null,new String[][]{{null, "13100000002"}}, null,null,null,null,null);
        /*CustomerParam customerParam = new CustomerParam(null, null, null, "韩总", null, null, "技术经理", null, null, null, new String[][]{{null, "13200000006"}}, null, null, null);
        createCustom(new CustomerCreateParam(customerParam, null, null));*/
        //getCustomDetail("cellphone","13100000002");

    }

    public static byte[] InputStreamToByte(InputStream iStrm) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = iStrm.read()) != -1)
        {
            bytestream.write(ch);
        }
        byte imgdata[]=bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    private static String getFileName(MultipartFile multipartFile){
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = null;

        if (multipartFile.getOriginalFilename()!=null && multipartFile.getOriginalFilename() !=""){
            originalFilename = multipartFile.getOriginalFilename();
        }else {
            originalFilename = multipartFile.getName();
        }

        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        return uuid+extName;
    }

}
